package com.stu.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.stu.entity.service.News;

/**
 * 抓取  http://it.sohu.com/itguonei.shtml 页面上的新闻
 * 	建议对每条新闻的每个属性都判空，防止因为网速原因造成属性为null
 * @author lijian
 *
 */
public class NewsUtils implements LoggerUtils{
	
	/**
	 * 封装新闻信息
	 * @author lijian
	 *
	 * @param element
	 * @return
	 */
	private static List<News> getNewsInfo(Element element) {
		Elements links = element.getElementsByTag("a");
		String link="";
		String title="";
		String summary="";
		String newsTime="";
		List<News>newsList=new ArrayList<News>();
		News news=null;
		
		for(int i=0;i<links.size();i++){
			news=new News();
			Element e=links.get(i);
			if(i%2==0){
				link=e.attr("href");
				title=e.text().trim();
			}else{
				summary=e.text().trim();
				newsTime=e.parent().parent().getElementsByTag("span").get(0).text().trim();//获取 新闻时间
				news.setCreateTime(new Date());
				news.setTitle(title);
				news.setLink(link);
				news.setSummary(summary);
				news.setNewsTime(newsTime);
				news.setContent(getContent(link)+"");
				newsList.add(news);
			}
		}
		return newsList;
	}

	/**
	 * 获取新闻内容
	 * @author lijian
	 *
	 * @param linkHref
	 * @return
	 */
	private static String getContent(String linkHref) {
		Document doc;
		try {
			doc = Jsoup.connect(linkHref).get();
			Elements ListDiv = doc.getElementsByAttributeValue("itemprop", "articleBody");
			for (Element element : ListDiv) {
				return element.html();
			}
		} catch (IOException e) {
			logger.error(e);
//			throw new RuntimeException(e);
		}
		return null;
	}
	
	/**
	 * 获取新闻
	 * @author lijian
	 *	建议对每一个属性都判空，防止因为网速原因造成某些属性为 null
	 * @return List<News> 
	 * @throws IOException
	 */
	public static List<News> getNews() throws IOException{
		Elements elements=JsoupUtils.getElementsByAttributeValue("http://it.sohu.com/itguonei.shtml", "class", "txt01");
		List<News>newsList=null;
		for(int i=0;i<elements.size();i++){
			Element element = elements.get(i);
			newsList=getNewsInfo(element);//获取  新闻信息
		}
		return newsList;
	}
	
//	public static void main(String[] args) throws IOException {
////		System.out.println(getNews());
//	}
}
